package com.xxg.renrenlogin.manager.wechat;

import com.alibaba.fastjson.JSON;
import com.xxg.renrenlogin.domain.result.AccessTokenResult;
import com.xxg.renrenlogin.exception.ErrorMessage;
import com.xxg.renrenlogin.exception.WeChatException;
import com.xxg.renrenlogin.util.RedisUtil;
import com.xxg.renrenlogin.util.RestServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 微信服务接口
 *
 * @author xxg
 * @date 2020/9/28
 */
@Component
public class WeChatManager {
    private static final Logger logger = LoggerFactory.getLogger(WeChatManager.class);

    @Value(value = "${wechat.lpAppid}")
    private String lpAppid;

    @Value(value = "${wechat.lpAppSecret}")
    private String lpAppSecret;


    /**
     * 获取微信CodeSession(小程序登录凭证校验)
     *
     * @param code 微信code
     * @return 微信AccessToken
     * @throws WeChatException 微信接口异常
     */
    public AccessTokenResult code2Session(String code) throws WeChatException {
        String serviceUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + lpAppid
                + "&secret=" + lpAppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        AccessTokenResult result;
        try {
            String resultStr = RestServiceUtil.remoteGetCall(serviceUrl, String.class);
            result = JSON.parseObject(resultStr, AccessTokenResult.class);
        } catch (Exception e) {
            logger.error(ErrorMessage.WECHAT_ERROR + "\n接口:"
                    + serviceUrl + "\n参数:" + code + "\n错误信息:" + e.getMessage(), e);
            throw new WeChatException(ErrorMessage.WECHAT_ERROR);
        }
        return result;
    }

}
